<template>
  <div class="assign-role">
    <el-dialog title="分配角色" :visible="showAssignRole" :close-on-click-modal="false" @open="openDialog" @close="closeAssinRoleDialog">
      <el-checkbox-group v-model="roleIdList" v-loading="isLoading">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button type="primary" @click="assignRole">确定</el-button>
        <el-button @click="closeAssinRoleDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserInfoApi } from '@/api/user'
import { assignRoleApi } from '@/api/empolyees'
export default {
  name: 'AssignRole',
  props: {
    userId: {
      type: String,
      default: ''
    },
    showAssignRole: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleList: [],
      roleIdList: [],
      isLoading: false
    }
  },
  methods: {
    /**
     * 获取所有的角色列表
     */
    async getRoleList() {
      const { data: { rows }} = await getRoleListApi(1, 9999)
      this.roleList = rows
    },
    /**
     * 获取用户原有的角色信息
     */
    async getUserInfo() {
      const { data: { roleIds }} = await getUserInfoApi(this.userId)
      this.roleIdList = roleIds || []
    },
    /**
    * 分配角色
    */
    async assignRole() {
      await assignRoleApi({
        id: this.userId,
        roleIds: this.roleIdList
      })
      this.$message.success('恭喜！分配成功')
      this.closeAssinRoleDialog()
    },
    /**
     * 打开弹框 执行的事件
     */
    openDialog() {
      // Promise.all([promise1,promise2]).then(res=>{})
      this.isLoading = true
      Promise.all([this.getRoleList(), this.getUserInfo()]).then(() => {
        // 表示这两个接口 都已经请求成功了
        this.isLoading = false
      })
    },
    /**
     * 关闭弹框
     */
    closeAssinRoleDialog() {
      // 固定语法：this.$emit('update:props中的值',修改值)
      this.$emit('update:showAssignRole', false)
    }
  }
}
</script>

<style>

</style>
